//
//  PilotTabViewController.m
//  EVETracker
//
//  Created by Scott Guyer on 7/16/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "RootPilotViewController.h"
#import "PilotTabViewController.h"
#import "PilotPageViewController.h"
#import "defs.h"



@interface PilotTabViewController (PrivateMethods)

- (void)loadScrollViewWithPage:(int)page;
- (void)scrollViewDidScroll:(UIScrollView *)sender;

@end



@implementation PilotTabViewController

@synthesize rootPilotVC;


@synthesize scrollView, pageControl;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		NSArray* nibObjects = [[NSBundle mainBundle] loadNibNamed:nibNameOrNil owner:self options:nil];
		if ( nibObjects == nil )
		{
			NSLog(@"%s can't load nib %@", __FUNCTION__, nibNameOrNil);
			return nil;
		}
		
		[self.view setAutoresizesSubviews:YES];
		
		_pages = [[NSMutableArray alloc] init];
				
		[pageControl setNumberOfPages:1];
		[pageControl setCurrentPage:0];
		[pageControl setDefersCurrentPageDisplay:YES];
		
		
		// a page is the width of the scroll view
		scrollView.pagingEnabled = YES;
		CGSize st = CGSizeMake(scrollView.frame.size.width * [_pages count], scrollView.frame.size.height);
		scrollView.contentSize = st;
		scrollView.showsHorizontalScrollIndicator = NO;
		scrollView.showsVerticalScrollIndicator = NO;
		scrollView.scrollsToTop = NO;
		scrollView.delegate = self;
		
		[self loadScrollViewWithPage:0];
		[self loadScrollViewWithPage:1];
	}
	
	return self;
}



- (void) resyncModel
{	
	// The idea here is to resync the view state between pilots and our view controllers
	// This happens when we alter the pilot list through the settings UI.  We may add or remove
	// pilots, or even reorder them.
	int numPilots = [_pilots count];
	int numPages = [_pages count];
	
	NSMutableArray* newPages = [[NSMutableArray alloc] initWithCapacity:numPilots];
	
	pageControl.numberOfPages = numPilots;

	CGSize st = CGSizeMake(scrollView.frame.size.width * numPilots, scrollView.frame.size.height);
	[scrollView setContentSize:st];
	
	int min = (numPilots < numPages) ? numPilots : numPages;
	for ( int i=0; i<min; i++ )
	{
		[newPages addObject:[_pages objectAtIndex:i]];
	}
		
	for ( int i=numPages; i<numPilots; i++ )
	{
		[newPages addObject:[NSNull null]];
	}
	
	if ( _pages != nil )
	{
		[_pages removeAllObjects];
		[_pages release];
	}
	
	_pages = newPages;
}



- (void)loadScrollViewWithPage:(int)page 
{	
    if (page < 0) return;    
	if (page >= [_pilots count]) return;

    // replace the placeholder if necessary
	PilotPageViewController* pvc;
	id controller = [_pages objectAtIndex:page];
	if ((controller == nil) || ![controller isKindOfClass:[UIViewController class]]) {
		pvc = [[PilotPageViewController alloc] initWithNibName:@"PilotPage" bundle:nil];
		pvc.rootPilotVC = self.rootPilotVC;
		[_pages replaceObjectAtIndex:page withObject:pvc];
		pvc.idx = page;
		pvc.parentVC = self;
		[pvc release];
		[controller release];
	}
	else
		pvc = (PilotPageViewController*)controller;	
	
	Character* c = (Character*) [_pilots objectAtIndex:page];
	if ( ! [c isEqual:pvc.pilot] )
	{
		pvc.pilot = c;
		NSLog(@"%s 0x%x retainCount=%d", __FUNCTION__, c, [c retainCount]);
		pvc.portraitNeedsReload = YES;		
		[pvc reloadData]; 
	}
		
    // add the controller's view to the scroll view
    if (nil == pvc.view.superview) {
        CGRect frame = scrollView.frame;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0;
		frame.size.height -= 2;
        pvc.view.frame = frame;
        [scrollView addSubview:pvc.view];
    }
	

}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
	[pageControl updateCurrentPageDisplay];
	
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    [self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    [self loadScrollViewWithPage:page + 1];
	
    // A possible optimization would be to unload the views+controllers which are no longer visible
}

- (IBAction)changePage:(id)sender {
	int page = pageControl.currentPage;
//	[pageControl updateCurrentPageDisplay];
	
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    [self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    [self loadScrollViewWithPage:page + 1];
    // update the scroll view to the appropriate page
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    [scrollView scrollRectToVisible:frame animated:YES];
}


- (void) setPilotList:(NSMutableArray*)pilots
{	
	if ( _pilots != nil )
	{
		[_pilots release]; 
	}
	_pilots = pilots;
	[_pilots retain];
	
	// Allocate new pages array and copy over existing items
	NSMutableArray* _newPages = [[NSMutableArray alloc] initWithCapacity:[_pilots count]];
	for ( int i=0; i < [_pilots count]; i++ )
	{
		if ( i < [_pages count] )
			[_newPages addObject:[_pages objectAtIndex:i]];
		else
			[_newPages addObject:[NSNull null]];
	}
	[_pages release]; 
	_pages = _newPages;
	
	CGSize st = CGSizeMake(scrollView.frame.size.width * [_pilots count], scrollView.frame.size.height);
	[scrollView setContentSize:st];
	
	[self loadScrollViewWithPage:0];
	[self loadScrollViewWithPage:1];
	
	[pageControl setNumberOfPages:[_pilots count]];
	pageControl.currentPage = 0;
	[pageControl updateCurrentPageDisplay];
}

- (void) viewDidAppear:(BOOL)animated
{
	NSLog(@"%s", __FUNCTION__);
}

- (void) viewWillAppear:(BOOL)animated
{
	NSLog(@"%s", __FUNCTION__);
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}




- (void) didReceiveMemoryWarning
{
}


- (void)dealloc 
{
	NSLog(@"%s 0x%x", __FUNCTION__, self);
	
	WIPE( scrollView)
	WIPE( pageControl)
	WIPE( rootPilotVC)
	WIPE( _pilots)
	WIPE( _pages)
	
	[super dealloc];
}


@end
